package com.voda.dao.impl;

import javax.persistence.PersistenceException;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.stereotype.Repository;

import com.voda.dao.api.IUserDao;
import com.voda.dao.impl.common.AbstractDaoImpl;
import com.voda.entity.User;

@Repository
public class UserDaoImpl extends AbstractDaoImpl<User> implements IUserDao {

	private static final String ID_PROP = "id";
	private static final String ROLE_PROP = "role";
	private static final String PASSWORD_PROP = "password";
	private static final String EMAIL_PROP = "email";
	private static final String USER_INFO = "userInfo";

	public UserDaoImpl() {
		super(User.class);
	}

	@Override
	public User findUser(String login, String password) {
		
		Criteria criteria = getSession().createCriteria(User.class);
		criteria.add(Restrictions.eq(EMAIL_PROP, login));
		criteria.add(Restrictions.eq(PASSWORD_PROP, password));
		criteria.createCriteria(ROLE_PROP, JoinType.LEFT_OUTER_JOIN);
		return (User) criteria.uniqueResult();
	}
	
	@Override
	public User getRecordById(Long id) throws PersistenceException {
		Criteria criteria = getSession().createCriteria(User.class);
		criteria.add(Restrictions.eq(ID_PROP, id));
		criteria.createCriteria(ROLE_PROP, JoinType.LEFT_OUTER_JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return (User) criteria.uniqueResult();
	}
	

	@Override
	public User getUserWithRole(Long id) {
		Criteria criteria = getSession().createCriteria(User.class);
		criteria.add(Restrictions.eq(ID_PROP, id));
		criteria.setFetchMode(ROLE_PROP, FetchMode.JOIN);
		criteria.setFetchMode(USER_INFO, FetchMode.JOIN);
		return (User) criteria.uniqueResult();
	}

	@Override
	public boolean checkUnique(String name) {
		Criteria criteria = getSession().createCriteria(User.class);
		criteria.add(Restrictions.eq(EMAIL_PROP, name)).setProjection(Projections.rowCount());
		if((Long)criteria.uniqueResult() == 0){
			return true;
		}
		return false;
	}

	@Override
	public User getUserByEmail(String email) {
		Criteria criteria = getSession().createCriteria(User.class);
		criteria.add(Restrictions.eq(EMAIL_PROP, email));
		return (User) criteria.uniqueResult();
	}

}
